<?php

namespace App\Exports\Flight;

use App\Services\Flight\FlightSearchService;
use Maatwebsite\Excel\Concerns\FromCollection;

class FlightPriceSpaceExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        //
        $data[] = [
            '日期',
            '航班号',
            '起飞',
            '到达',
            '最低价格',
            '最高价格',
        ];

        $flightDynamicService = new FlightSearchService();
        $interface = resolve('App\Repositories\Contracts\FlightDynamicInterface');
        $whereIn = $flightDynamicService->searchFlightDynamic(request());
        $where = [];
        if (request()->start_at){
            $where[] = ['created_at','>=',substr(request()->start_at,0,10)];
        }

        $dynamics = $interface->get($where,'*',[],'id','desc','flight_id',$whereIn);

        if ($dynamics->isNotEmpty()) {


            foreach ($dynamics as $key => $value) {

                try {

                    $sumDelayRate = sprintf('%.2f',($value['dep_delay_inThirtyM'] + $value['dep_delay_thirtyMToOneH'] + $value['dep_delay_oneHToThreeH'] + $value['dep_delay_overThreeH']) / 100);
                    $sumDelayRate = 30 * $sumDelayRate;


                    $sumScheduleRate = sprintf('%.2f',($value['dep_delay_thirtyMToOneH'] + $value['dep_delay_oneHToThreeH'] + $value['dep_delay_overThreeH'] + ($value['scheduleChange_rate'] ? : 0))/100);
                    $sumDelayRate = $sumDelayRate * $sumScheduleRate;
                    $sumDelayRate = sprintf('%.2f',$sumDelayRate /30);
                    if ( $sumDelayRate >= 0.6 ) {

                        for ($priceIndex = 3; $priceIndex <= 19; $priceIndex++) {

                            $data[] = [

                                $value->created_at->format('Y-m-d'),
                                $value['flight_code'],
                                $value['dep_code'],
                                $value['arr_code'],
                                $priceIndex * 100 + 1,
                                ($priceIndex + 1) * 100,

                            ];
                        }
                    }

                } catch (\Exception $exception){

                    //dd($value);
                }
            }
        }

            return collect($data);
    }
}
